package com.ybkj.daijia.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybkj.daijia.common.FileUploadVo;
import com.ybkj.daijia.common.MediaUtil;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.InforMation;
import com.ybkj.daijia.server.service.InforMationService;
import com.ybkj.daijia.server.service.MemberService;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;


/**
 * @author LiYunHao.
 */
@RestController
@RequestMapping(value = "information")
public class InforMationController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private InforMationService inforMationService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentinformation")) {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("information/list");
            return modelAndView;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "pass", method = RequestMethod.GET)
    public ModelAndView pass(@RequestParam("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentinformation")) {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("id", id);
            modelAndView.setViewName("information/pass");
            return modelAndView;
        } else {
            throw new NoPermissionException();
        }
    }

    //分页
    @RequestMapping(value = "selectInforMation", method = RequestMethod.GET)
    public Page<InforMation> selectInforMation(
        @RequestParam(required = false, value = "nameOrPhone") String nameOrPhone,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "isPass") Integer isPass,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
//		Subject subject = SecurityUtils.getSubject();
//		if (subject.isPermitted("brand")) {
//		ModelAndView mv = new ModelAndView();

        return inforMationService.selectInforMation(nameOrPhone, page, rows, isPass);
//		 Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
//		return new PageImpl<InforMation>(list, pageable, total);

    }

    @RequestMapping(value = "selectById", method = RequestMethod.GET)
    public InforMation selectById(
        @RequestParam(required = false, value = "id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        return inforMationService.selectById(id);
    }


    @RequestMapping(value = "updateInforMation", method = RequestMethod.POST)
    public Map<String, Object> updateInforMation(
        @RequestParam("id") Long id,
        @RequestParam("idcardpositiveresult") Integer idcardpositiveresult,
        @RequestParam("idcardbackresult") Integer idcardbackresult,
        @RequestParam("driverresult") Integer driverresult,
        @RequestParam("idcardpositiveremarks") String idcardpositiveremarks,
        @RequestParam("idcardbackremarks") String idcardbackremarks,
        @RequestParam("driverremarks") String driverremarks,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        return inforMationService
            .updateInforMation(id, idcardpositiveresult, idcardbackresult, driverresult,
                idcardpositiveremarks, idcardbackremarks, driverremarks);

    }


    @RequestMapping(value = "insertinformation", method = RequestMethod.POST)
    public Map<String, Object> insertInforMation(
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "idcard") String idcard,
        @RequestParam(required = false, value = "drivernumber") String drivernumber,
        @RequestParam(required = false, value = "photourl") String photourl,
        @RequestParam(required = false, value = "registrationtime") Integer registrationtime,
        @RequestParam(required = false, value = "reviewer") String reviewer,
        @RequestParam(required = false, value = "idcardpositivephoto") String idcardpositivephoto,
        @RequestParam(required = false, value = "idcardbackphoto") String idcardbackphoto,
        @RequestParam(required = false, value = "driverphoto") String driverphoto,
        @RequestParam(required = false, value = "idcardpositiveresult") Integer idcardpositiveresult,
        @RequestParam(required = false, value = "idcardbackresult") Integer idcardbackresult,
        @RequestParam(required = false, value = "driverresult") Integer driverresult,
        @RequestParam(required = false, value = "idcardpositiveremarks") String idcardpositiveremarks,
        @RequestParam(required = false, value = "idcardbackremarks") String idcardbackremarks,
        @RequestParam(required = false, value = "driverremarks") String driverremarks,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        return inforMationService
            .insertInforMation(phone, name, idcard, drivernumber, photourl, registrationtime,
                reviewer, idcardpositivephoto, idcardbackphoto, driverphoto, idcardpositiveresult,
                idcardbackresult, driverresult, idcardpositiveremarks, idcardbackremarks,
                driverremarks);
    }


    @RequestMapping(value = "batchpass", method = RequestMethod.POST)
    public Map<String, Object> batchpass(
        @RequestParam(required = false, value = "size") String size,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        return inforMationService.batchpass(size);
    }


    /**
     * 上传司机照片
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value = "uploadDriverImage", method = RequestMethod.POST)
    public void uploadDriverImage(
        @RequestParam("pic1") MultipartFile pic1,
        @RequestParam("type") String type,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {

        FileUploadVo vo = new FileUploadVo();

        String moduleName = pic1.getOriginalFilename();

        if (MediaUtil.isPicture(pic1, "")) {

            long maxSize = 2000000;
            if (pic1.getSize() <= maxSize) {
                String bathPath = getBasePath(req);

                File tempDir = new File(bathPath, "upload/drivertemp");

                FileUtils.forceMkdir(tempDir);

                String uid = UUID.randomUUID().toString().replaceAll("-", "");

                String fileName = String.format("%s.jpg", uid);

                byte[] data = pic1.getBytes();

                File newFile = new File(tempDir, fileName);
                //InputStream in = req.getInputStream();
                FileOutputStream out = new FileOutputStream(newFile);
                IOUtils.write(data, out);

                try {

                    int length = 400;
                    if (StringUtils.isNotBlank(type) && type.equals("bigphoto")) {
                        length = 600;
                    }

                    // 读取源图像
                    BufferedImage bi = ImageIO.read(newFile);
                    int srcWidth = bi.getWidth(); // 源图宽度
                    int srcHeight = bi.getHeight(); // 源图高度

                    if (srcWidth > length || srcHeight > length) {
                        int _width = 0;
                        int _height = 0;
                        if (srcWidth > srcHeight) {
                            _width = length;
                            _height = (srcHeight * length) / srcWidth;
                        } else {
                            _height = length;
                            _width = (srcWidth * length) / srcHeight;
                        }
                        Thumbnails.of(newFile).size(_width, _height).toFile(newFile);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                IOUtils.closeQuietly(out);

                vo.setUrl(fileName);
                vo.setSuccess(true);
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            } else {
                vo.setSuccess(false);
                vo.setMsg("图片不能超过大小限制2M");
                resp.setContentType("text/html;charset=UTF-8");
                resp.setCharacterEncoding("utf-8");
                Writer writer = resp.getWriter();

                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(writer, vo);
            }
        } else {
            vo.setSuccess(false);
            vo.setMsg("只能上传图片");
            resp.setContentType("text/html;charset=UTF-8");
            resp.setCharacterEncoding("utf-8");
            Writer writer = resp.getWriter();

            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(writer, vo);
        }

    }


    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


}
